package com.example.java3mysql.controller;

import com.example.java3mysql.dao.JpaStudent;
import com.example.java3mysql.entity.HomeAddress;
import com.example.java3mysql.entity.Student;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Random;

@RestController
public class StudentApi {
    @Resource
    private JpaStudent jpaStudent;
    @GetMapping("/students")
    public List<Student> getAll(){
        return jpaStudent.findAll();
    }
    @Transactional
    @DeleteMapping("/students")
    public void deleteAll(){
        jpaStudent.deleteAll();
    }
    @GetMapping("/student/{studentCode}")
    public Student getOne(@PathVariable String studentCode){
        return jpaStudent.findByStudentCode(studentCode);
    }
    @DeleteMapping("/student/{studentCode}")
    public void deleteOne(@PathVariable String studentCode){
        jpaStudent.deleteByStudentCode(studentCode);
    }

    private Random random = new Random();

    @PutMapping("/student")
    public Student saveOne(@RequestBody Student student){
        student.setStudentCode("S_"+String.format("%06d",random.nextInt(100000)));
        return jpaStudent.save(student);
    }
    @PostMapping("/student")
    public Student updateOne(@RequestBody Student student){
        Student temp = jpaStudent.findByStudentCode(student.getStudentCode());
        if (temp == null) throw new RuntimeException(student.toString());
        student.setId(temp.getId());
        return jpaStudent.save(student);
    }
    @PatchMapping("/student_address/{studentCode}")
    public Student updatePart(@PathVariable String studentCode,
                              @RequestBody HomeAddress homeAddress){
        Student student = jpaStudent.findByStudentCode(studentCode);
        if (student == null ) throw new RuntimeException(student.toString());
        student.setHomeAddress(homeAddress);
        return jpaStudent.save(student);
    }

}
